import dayjs from 'dayjs'
import { formatNumber } from './util'

// 日期格式化
export function formatTimestamp (timestamp, type, CHflag) {
  var date = new Date()
  date.setTime(timestamp)

  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()
  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  switch (type) {
    case 'date':
      if (CHflag) {
        return formatNumber(year) + '年' + formatNumber(month) + '月' + formatNumber(day) + '日'
      }
      return formatNumber(year) + '-' + formatNumber(month) + '-' + formatNumber(day)
    case 'time':
      return formatNumber(hour) + ':' + formatNumber(minute)
    case 'monthDate':
      if (CHflag) {
        return month + '月' + day + '日'
      }
      return formatNumber(month) + '-' + formatNumber(day)
    case 'yearMonth':
      if (CHflag) {
        return formatNumber(year) + '年' + month + '月'
      }
      return formatNumber(year) + '-' + formatNumber(month)
    case 'dateTime':
      if (CHflag) {
        return (
          formatNumber(year) +
          '年' +
          formatNumber(month) +
          '月' +
          formatNumber(day) +
          '日' +
          ' ' +
          formatNumber(hour) +
          ':' +
          formatNumber(minute) +
          formatNumber(second)
        )
      }
      break
    default:
      return (
        formatNumber(year) +
        '-' +
        formatNumber(month) +
        '-' +
        formatNumber(day) +
        ' ' +
        formatNumber(hour) +
        ':' +
        formatNumber(minute) +
        ':' +
        formatNumber(second)
      )
  }
}

// 获取当前当前周的每天的日期
export function getDateFromWeek (day) {
  const isoWeek = require('dayjs/plugin/isoWeek')
  dayjs.extend(isoWeek)

  let startDateString = ''
  let endDateString = ''
  const dateArr = []
  day = day ? dayjs(day) : dayjs()
  for (let i = 0; i < 7; i++) {
    const date = day.isoWeekday(1).add(i, 'd').toDate()
    if (i === 0) {
      startDateString = formatTimestamp(date, 'date', true)
    }
    if (i === 6) {
      endDateString = formatTimestamp(date, 'date', true)
    }
    dateArr.push(formatTimestamp(date, 'date'))
  }
  const weekDurantion = {
    startDateString,
    endDateString,
    dateArr: dateArr
  }
  return weekDurantion
}

// 获取两个日期之间的所有日期
export function getInDates (begin, end) {
  const dateArr = []
  for (let i = 0; i < 7; i++) {
    const date = dayjs(begin).add(i, 'days').toDate()
    dateArr.push(formatTimestamp(date, 'date'))
  }

  // 返回两个日期之间的所有日期数组。
  return dateArr
}

export function getMonthFirst (date) {
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  const d = '01'
  m = m < 10 ? '0' + m : m

  return [y, m, d].join('-')
}

export function getMonthLast (date) {
  const y = date.getFullYear()
  let m = date.getMonth() + 1
  let d = new Date(y, m, 0).getDate()
  m = m < 10 ? '0' + m : m
  d = d < 10 ? '0' + d : d

  return [y, m, d].join('-')
}
